package me.zhengjie.modules.quartz.task.count;

import com.alibaba.fastjson.JSON;
import com.qiaofang.applet.service.other.service.SynchronousDataService;
import com.qiaofang.applet.service.other.service.dto.CountSynDataDto;
import com.qiaofang.applet.service.property.service.DataProcessingErrorLogService;
import com.qiaofang.applet.service.property.service.SyncDataLogService;
import com.qiaofang.applet.service.property.service.SyncDataQueueService;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.quartz.service.dto.SyncCommon;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.Date;

/*
 * 统计数据基类
 * */
@Slf4j
public abstract class CountBase {

    @Autowired
    SyncDataQueueService syncDataQueueService;

    @Autowired
    SyncDataLogService syncDataLogService;

    @Autowired
    SynchronousDataService synchronousDataService;

    @Autowired
    DataProcessingErrorLogService dataProcessingErrorLogService;

    protected SyncCommon syncCommon;

    public void pull(SyncCommon syncCommon, String synchronousType) {
        try {
            this.syncCommon = syncCommon;
            synchronousDataService.deleteDataToWeek(syncCommon.getCorporationCode(), syncCommon.getCompanyUuid());
            CountSynDataDto countSynDataDto = new CountSynDataDto();
            BeanUtils.copyProperties(syncCommon, countSynDataDto);
            countSynDataDto.setSynchronousType(synchronousType);
            countSynDataDto.setUpdateTime(getDayZero(DateUtils.addDays(new Date(), -1)));
            synchronousDataService.refreshSynCount(countSynDataDto);
        } catch (Exception e) {
            log.error("count prams {},error {}", JSON.toJSONString(syncCommon), e);
        }
    }

    private Date getDayZero(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
}
